package com.hexun.dubbo.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jsonp filter
 */
public class JsonpFilter implements Filter {

    protected String jsonp = "callback";

    /**
     * 判断是否是jsonp请求（参数是否带callback）
     *
     * @param req servlet request
     * @return whether is jsonp
     */
    protected boolean isJsonp(ServletRequest req) {
        return req instanceof HttpServletRequest && req.getParameterMap().containsKey(jsonp);
    }

    /**
     * 获取callback的key
     *
     * @param req Servletequest
     * @return
     */
    private String getCallback(ServletRequest req) {
        return req.getParameterValues(jsonp)[0];
    }

    /**
     * @param req
     * @param resp
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(final ServletRequest req, final ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {

        if (resp instanceof HttpServletResponse && isJsonp(req)) {
            JsonpResponseWrapper wrapper = new JsonpResponseWrapper(
                    (HttpServletResponse) resp, getCallback(req));
            chain.doFilter(req, wrapper);
            wrapper.flushWrapper();
        } else {
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {

    }
}
